﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ciloci.Flee;

namespace OpenExpressApp.Expression
{
    public class ObjectExprParser
    {
        private ExpressionContext context;

        public ObjectExprParser(Type ownerType)
            : this(Activator.CreateInstance(ownerType))
        {
        }

        public ObjectExprParser(object owner)
        {
            context = new ExpressionContext(owner);
            context.Imports.AddType(typeof(CustomFunctions));
            //context.Imports.AddType(typeof(Convert));
        }

        public string Expression { get; private set; }
        private IDynamicExpression dynamicExpression; 
        public IDynamicExpression Compile(string expr)
        {
            this.Expression = expr;
            dynamicExpression = context.CompileDynamic(expr);
            return dynamicExpression;
        }

        public object Evaluate(object owner)
        {
            dynamicExpression.Owner = owner;
            return dynamicExpression.Evaluate();
        }

        public object Execute(string expr, object owner)
        {
            Compile(expr);
            return Evaluate(owner);
        }
    }
}
